<template>
    <div class="create-site-container">
        <div class="header">
            <h2>{{ isEditMode ? '编辑站点' : '创建站点' }}</h2>
            <div>
                <!-- <el-button @click="resetForm">重置</el-button> -->
                <!-- <el-button type="primary" @click="submitForm">{{ isEditMode ? '更新站点' : '创建站点' }}</el-button> -->
            </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-overlay">
            <div class="loading-spinner"></div>
            <div class="loading-text">加载中，请稍候...</div>
        </div>

        <div class="card">
            <div class="card-header">基础信息</div>
            <div class="card-body">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                    <div class="form-row">
                        <div class="form-col">
                            <el-form-item label="站点名称" prop="activity_name">
                                <el-input v-model="form.activity_name" placeholder="请输入站点名称" clearable />
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="品牌客户" prop="customer">
                                <el-input v-model="form.customer" placeholder="请输入品牌客户" clearable />
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="运营地点" prop="area">
                                <el-cascader v-model="form.area" :options="areaOptions" placeholder="请选择省/市" :props="{
                                    expandTrigger: 'hover',
                                    value: 'value',
                                    label: 'label',
                                    children: 'children'
                                }" filterable clearable style="width: 100%" />
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="开展日期" prop="startdate">
                                <el-date-picker v-model="form.startdate" type="date" placeholder="选择日期"
                                    value-format="YYYY-MM-DD" style="width: 100%" />
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="结束日期" prop="enddate">
                                <el-date-picker v-model="form.enddate" type="date" placeholder="选择日期"
                                    value-format="YYYY-MM-DD" style="width: 100%" />
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="站点类型" prop="level">
                                <el-radio-group v-model="form.level">
                                    <el-radio :label="1">小程序</el-radio>
                                    <el-radio :label="2">H5</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="后台显示" prop="is_show">
                                <el-radio-group v-model="form.is_show">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="站点状态" prop="status">
                                <el-radio-group v-model="form.status">
                                    <el-radio :label="1">启用</el-radio>
                                    <el-radio :label="0">停用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                    </div>
                </el-form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">高级配置</div>
            <div class="card-body">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                    <div class="form-row">
                        <div class="form-col">
                            <el-form-item label="App Key" prop="app_key">
                                <el-input v-model="form.app_key" placeholder="请输入App Key" clearable />
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="App Secret" prop="app_secret">
                                <el-input v-model="form.app_secret" placeholder="请输入App Secret" clearable
                                    show-password />
                            </el-form-item>
                        </div>

                        <div class="form-col">
                            <el-form-item label="留资验证类型" prop="check_phone_type">
                                <el-radio-group v-model="form.check_phone_type">
                                    <el-radio :label="0">无验证</el-radio>
                                    <el-radio :label="1">微信授权</el-radio>
                                    <el-radio :label="2">短信验证码</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                    </div>

                    <div class="form-section">
                        <div class="form-title">留资导出配置</div>
                        <div class="option-description">
                            请选择站点需要的留资导出配置（可多选）
                        </div>

                        <!-- 系统字段部分 -->
                        <div class="field-section">
                            <h3 class="field-title">系统字段</h3>
                            <div class="field-container">
                                <div v-for="(value, key) in getUserValuesList" :key="'system_' + key"
                                    class="field-item">
                                    <!-- {{ value.key }} -->
                                    <template v-if="form.option.systemFields[value.key]">
                                        <label class="flex fd-c cursor-pointer w-full">
                                            
                                            <el-checkbox v-model="form.option.systemFields[value.key].checked"
                                                @change="(val) => handleCheckChange('system', value.key, val)"
                                                class="field-checkbox">
                                                {{ value.key }}
                                            </el-checkbox>
                                            <div class="field-identifier">标识: {{ value.key }}</div>
                                            <el-input v-model="form.option.systemFields[value.key].value" placeholder="输入表头名称"
                                                class="field-input" @change="handleLabelChange('system', value.key)" />
                                        </label>
                                    </template>
                                </div>
                            </div>
                        </div>

                        <!-- 项目字段部分 -->
                        <div v-if="projectList.length > 0 && isEditMode" class="field-section">
                            <h3 class="field-title">项目字段</h3>
                            <div class="field-container">
                                <div v-for="(project, index)  in projectList" :key="'project_' + project.id" class="field-item">
                                    <!-- {{ project }} -->
                                    <template v-if="form.option.projectFields[`${project.pid}_${project.key}`]">
                                        <label class="flex fd-c cursor-pointer w-full">
                                            <el-checkbox v-model="form.option.projectFields[`${project.pid}_${project.key}`].checked"
                                                @change="(val) => handleCheckChange('project', `${project.pid}_${project.key}`, val)"
                                                class="field-checkbox">
                                                {{ project.label }}
                                            </el-checkbox>
                                            <div class="field-identifier">项目ID: {{ project.pid }}</div>
                                            <el-input v-model="form.option.projectFields[`${project.pid}_${project.key}`].value"
                                                placeholder="输入表头名称" class="field-input"
                                                @change="handleLabelChange('project', `${project.pid}_${project.key}`)" />
                                        </label>
                                    </template>

                                </div>
                            </div>
                        </div>
                    </div>
                </el-form>
            </div>
        </div>



        <div class="site-preview" v-if="isEditMode">
            <div class="preview-header">基础信息预览</div>
            <div class="preview-grid">
                <div class="preview-item">
                    <div class="preview-label">站点名称</div>
                    <div class="preview-value">{{ form.activity_name }}</div>
                </div>
                <div class="preview-item">
                    <div class="preview-label">品牌客户</div>
                    <div class="preview-value">{{ form.customer || '未填写' }}</div>
                </div>
                <div class="preview-item">
                    <div class="preview-label">运营地点</div>
                    <div class="preview-value">{{ areaText }}</div>
                </div>
                <div class="preview-item">
                    <div class="preview-label">开展日期</div>
                    <div class="preview-value">{{ form.startdate || '未设置' }}</div>
                </div>
                <div class="preview-item">
                    <div class="preview-label">结束日期</div>
                    <div class="preview-value">{{ form.enddate || '未设置' }}</div>
                </div>
                <div class="preview-item">
                    <div class="preview-label">站点类型</div>
                    <div class="preview-value">{{ form.level === 1 ? '小程序' : 'H5' }}</div>
                </div>
                <div class="preview-item">
                    <div class="preview-label">验证类型</div>
                    <div class="preview-value">{{ getCheckTypeText(form.check_phone_type) }}</div>
                </div>
                <div class="preview-item">
                    <div class="preview-label">后台显示</div>
                    <div class="preview-value">{{ form.is_show === 1 ? '是' : '否' }}</div>
                </div>
                <div class="preview-item">
                    <div class="preview-label">站点状态</div>
                    <div class="preview-value">{{ form.status === 1 ? '启用' : '停用' }}</div>
                </div>
                <div class="preview-item full-width">
                    <div class="preview-label">留资导出配置</div>
                    <div class="preview-value">
                        <div v-if="isOptionEmpty" class="empty-options">无留资导出配置</div>
                        <div v-else>
                            <div v-for="(field, type) in previewOptions" :key="type" class="preview-category">
                                <div class="preview-category-title">{{ type === 'system' ? '系统字段' : '项目字段' }}</div>
                                <div class="options-container">
                                    <div v-for="(opt, idx) in field" :key="idx" class="option-item">
                                         <!-- ({{ opt.key }}) -->
                                        {{ opt.label }} ({{ opt.key }})
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <div class="form-actions">
            <el-button type="primary" size="large" @click="submitForm">{{ isEditMode ? '更新站点' : '创建站点' }}</el-button>
            <!-- <el-button size="large" @click="resetForm">重置</el-button> -->
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from "../libs/http";
import { provinceAndCityData } from 'element-china-area-data';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();

const formRef = ref(null);
const isEditMode = ref(false);
const newOption = ref('');
const loading = ref(false); // 加载状态
// 项目列表数据
const projectList = ref([]);
const getUserValuesList = ref(null);
// 表单数据
const form = reactive({
    activity_name: '',
    customer: '',
    area: [],
    startdate: '',
    enddate: '',
    level: 1,
    app_key: '',
    app_secret: '',
    check_phone_type: 0,
    // option: ['name', 'phone'],
    option: {
        systemFields: {},
        projectFields: {}
    },
    is_show: 1,
    status: 1
});
// 添加顺序计数器
const selectionOrderCounter = ref(1);

// 修改勾选处理函数
const handleCheckChange = (type, id, checked) => {
    if (type === 'system') {
        form.option.systemFields[id].checked = checked;
        if (checked) {
            form.option.systemFields[id].order = selectionOrderCounter.value++;
        } else {
            form.option.systemFields[id].order = 0; // 重置顺序
        }
    } else if (type === 'project') {
        form.option.projectFields[id].checked = checked;
        if (checked) {
            form.option.projectFields[id].order = selectionOrderCounter.value++;
        } else {
            form.option.projectFields[id].order = 0; // 重置顺序
        }
    }
};
// 计算属性：预览用的留资导出配置
// 修改 previewOptions 计算属性
const previewOptions = computed(() => {
    const result = {
        system: [],
        project: []
    };
    console.log('原始的留资导出配置结构:', form.option);
    console.log('projectList:', projectList);
    // 系统字段（按 order 排序）
    for (const [key, field] of Object.entries(form.option.systemFields)) {
        if (field.checked && field.order > 0) {
            result.system.push({
                key,
                label: field.value || key,
                order: field.order
            });
        }
    }
    // 按 order 升序排序
    result.system.sort((a, b) => a.order - b.order);

    // debugger
    // 项目字段（按 order 排序）
    for (const [id, field] of Object.entries(form.option.projectFields)) {
        if (field.checked && field.order > 0) {
            const project = projectList.value.find(p => `${field.pid}_${field.key}` == id);
            result.project.push({
                key: project ? `项目${field.pid}_${field.key}` : `项目${id}`,
                label: field.value  || (project ? project.play_name : `项目${id}`),
                order: field.order
            });
        }
    }
    // 按 order 升序排序
    result.project.sort((a, b) => a.order - b.order);
    console.log('预览的留资导出配置结构:', result);
    return result;
});
// 计算属性：留资导出配置是否为空
const isOptionEmpty = computed(() => {
    return (
        Object.values(form.option.systemFields).every(f => !f.checked) &&
        Object.values(form.option.projectFields).every(f => !f.checked)
    );
});
// 处理标签变化
const handleLabelChange = (type, id) => {
    // // 如果用户清空输入框，恢复默认值
    // if (type === 'system') {
    //     if (!form.option.systemFields[id].label && getUserValuesList.value) {
    //         form.option.systemFields[id].label = getUserValuesList.value[id] || id;
    //     }
    // } else if (type === 'project') {
    //     const project = projectList.value.find(p => p.id == id);
    //     if (!form.option.projectFields[id].label && project) {
    //         form.option.projectFields[id].label = project.play_name;
    //     }
    // }
};

// 初始化option结构
const initOptionStructure = () => {
    // 初始化系统字段
    if (getUserValuesList.value) {
        for (const [key, value] of Object.entries(getUserValuesList.value)) {
            form.option.systemFields[value.key] = {
                
                key: value.key,
                pid: value.pid,
                checked: false,
                label: value.value,
                value: value.value,
                order: 0 // 初始化顺序为0
            };

            // 特殊处理name和phone字段，将它们设为选中状态
            if (!isEditMode.value) {
                if (value.key === 'name' || value.key === 'phone') {
                    form.option.systemFields[value.key].checked = true;
                    // 为默认选中的字段设置初始顺序
                    form.option.systemFields[value.key].order = selectionOrderCounter.value++;
                }
            }
        }
    }


    // 初始化项目字段
    // for (const (project, index) of projectList.value) {
    for (const [index, project] of projectList.value.entries()) {
        form.option.projectFields[`${project.pid}_${project.key}`] = {
            key: project.key,
            pid: project.pid,
            checked: false,
            label: project.value,
            value: project.value,
            order: 0 // 初始化顺序为0
        };
    }

    console.log('初始化后的留资导出配置结构:', projectList.value);
    console.log('初始化后的留资导出配置结构:', form.option);
};
// 使用 element-china-area-data 提供的省市数据
const areaOptions = ref(provinceAndCityData);



// 表单验证规则
const rules = reactive({
    activity_name: [
        { required: true, message: '请输入站点名称', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
    ],
    customer: [
        { required: true, message: '请输入品牌客户', trigger: 'blur' },
    ],
    area: [
        { required: true, message: '请选择运营地点', trigger: 'change' }
    ],
    startdate: [
        { required: true, message: '请选择开展日期', trigger: 'change' }
    ],
    enddate: [
        { required: true, message: '请选择结束日期', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (form.startdate && value && value < form.startdate) {
                    callback(new Error('结束日期不能早于开始日期'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ],
    level: [
        { required: true, message: '请选择站点类型', trigger: 'change' }
    ],
    check_phone_type: [
        { required: true, message: '请选择验证类型', trigger: 'change' }
    ],
    is_show: [
        { required: true, message: '请选择是否在后台显示', trigger: 'change' }
    ],
    status: [
        { required: true, message: '请选择站点状态', trigger: 'change' }
    ]
});

// 计算属性：地区文本
const areaText = computed(() => {
    if (form.area.length === 0) return '未选择';

    const province = findAreaByValue(areaOptions.value, form.area[0]);
    if (!province) return '未选择';

    if (form.area.length > 1) {
        const city = findAreaByValue(province.children, form.area[1]);
        if (city) {
            return `${province.label} - ${city.label}`;
        }
    }

    return province.label;
});

// 添加选项
const addOption = () => {
    if (newOption.value && !form.option.includes(newOption.value)) {
        form.option.push(newOption.value);
        newOption.value = '';
    } else if (!newOption.value) {
        ElMessage.warning('请输入选项内容');
    }
};

// 删除选项
const removeOption = (index) => {
    form.option.splice(index, 1);
};

// 获取验证类型文本
const getCheckTypeText = (type) => {
    const types = {
        0: '无验证',
        1: '微信授权',
        2: '短信验证码'
    };
    return types[type] || '未知';
};

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields();
    }
    form.option = ['name', 'phone'];
    form.is_show = 1;
    form.status = 1;
    isEditMode.value = false;
};

// 提交表单
const submitForm = () => {
    formRef.value.validate(valid => {
        if (valid) {
            console.log('提交的数据:', form.option); // 打印提交的数据
            console.log('提交的数据:', form.option.projectFields); // 打印提交的数据
            console.log('提交的数据:', form.option.systemFields); // 打印提交的数据

            // return

            // 重构提交数据 - 只提交选中的留资导出配置
            const selectedOptions = [];
            // const selectedOptions = {
            //     systemFields: {},
            //     projectFields: {}
            // };
            // 处理系统字段（保留顺序）
            Object.keys(form.option.systemFields).forEach(key => {
                if (form.option.systemFields[key].checked) {
                    selectedOptions.push({
                        key: form.option.systemFields[key].key,
                        pid: form.option.systemFields[key].pid,
                        value: form.option.systemFields[key].value,
                        order: form.option.systemFields[key].order // 保存顺序
                    });
                    // selectedOptions.systemFields[key] = {
                    //     key: form.option.systemFields[key].key,
                    //     pid: form.option.systemFields[key].pid,
                    //     value: form.option.systemFields[key].value,
                    //     order: form.option.systemFields[key].order // 保存顺序
                    // }
                }
            });

            // 处理项目字段（保留顺序）
            Object.keys(form.option.projectFields).forEach(id => {
                if (form.option.projectFields[id].checked) {
                    selectedOptions.push({
                        key: form.option.projectFields[id].key,
                        pid: form.option.projectFields[id].pid,
                        value: form.option.projectFields[id].value,
                        order: form.option.projectFields[id].order // 保存顺序
                    });
                    // selectedOptions.projectFields[id] = {
                    //     key: form.option.projectFields[key].key,
                    //     pid: form.option.projectFields[key].pid,
                    //     value: form.option.projectFields[id].value,
                    //     order: form.option.projectFields[id].order // 保存顺序
                    // }
                }
            });
            loading.value = true;

            const submitData = {
                ...form,
                token: localStorage.getItem('openid'),
                id: route.query.site || 0,
                province: getProvinceName(),
                city: getCityName(),
                option: JSON.stringify(selectedOptions) // 只包含选中的字段
            };

            delete submitData.area;


            console.log('提交的selectedOptions数据:', selectedOptions);
            console.log('提交的数据:', submitData);

            // return;

            http.$post('hd_project/Backend/editActivity', submitData)
                .then(response => {
                    if (response.code !== 200) {
                        ElMessage.error(response.msg || '操作失败');
                        return;
                    }

                    ElMessage.success(isEditMode.value ? '站点更新成功！' : '站点创建成功！');

                    // 触发全局事件通知 HomeView2 更新站点列表
                    window.dispatchEvent(new CustomEvent('updateSiteList'));

                    // // 延迟跳转，让用户看到成功消息
                    // setTimeout(() => {
                    //     router.push('/');
                    // }, 1000);
                })
                .catch(error => {
                    console.error('操作失败:', error);
                    ElMessage.error('操作失败，请稍后重试');
                })
                .finally(() => {
                    loading.value = false;
                });
        } else {
            ElMessage.warning('请填写必填项');
        }
    });
};

// 获取省份中文名
const getProvinceName = () => {
    if (form.area.length === 0) return '';
    const province = findAreaByValue(areaOptions.value, form.area[0]);
    return province ? province.label : '';
};

// 获取城市中文名
const getCityName = () => {
    if (form.area.length < 2) return '';
    const province = findAreaByValue(areaOptions.value, form.area[0]);
    if (!province || !province.children) return '';

    const city = findAreaByValue(province.children, form.area[1]);
    return city ? city.label : '';
};

// 根据value值查找地区
const findAreaByValue = (areas, value) => {
    if (!areas) return null;
    return areas.find(area => area.value === value);
};

// 获取项目列表
const fetchProjects = async () => {
    try {
        // 模拟API请求
        const token = localStorage.getItem("openid");
        const params = {
            token,
            activity_id: route.query.site,
        };

        // 实际调用: 
        const response = await http.$post('hd_project/Backend/getProjectList', params);
        const mockData = response;



        if (mockData.code === 200) {
            projectList.value = mockData.data;
            // initOptionStructure(); // 初始化option结构
        } else {
            ElMessage.error('获取项目列表失败');
        }

    } catch (error) {
        console.error('获取项目列表错误:', error);
        ElMessage.error('获取项目列表失败');
    }
};
// 获取项目列表
const fetchProjects2 = async () => {
    try {
        // 模拟API请求
        const token = localStorage.getItem("openid");
        const params = {
            token,
            activity_id: route.query.site,
        };

        // 实际调用: 
        const response = await http.$post('hd_project/Backend/getProjectList2', params);
        const mockData = response;



        if (mockData.code === 200) {
            projectList.value = response.data.flat().map(item => ({
                ...item,
                checked: false,
                label: item.value,
                order: 0
            }));
            // projectList.value = mockData.data;
            // initOptionStructure(); // 初始化option结构
            console.log(projectList)
        } else {
            ElMessage.error('获取项目列表失败');
        }

    } catch (error) {
        console.error('获取项目列表错误:', error);
        ElMessage.error('获取项目列表失败');
    }
};

// 获取用户导出字段
const getUserValues2 = async () => {

    try {
        // 模拟API请求
        // const token = localStorage.getItem("openid");
        const params = {
            //   token,
            //   activity_id: route.query.site,
        };

        // 实际调用: 
        const response = await http.$get('hd_project/Backend/getUserValues2', params);
        const mockData = response;

        if (mockData.code === 200) {

              // 处理系统字段
              getUserValuesList.value = response.data
                .filter(item => item.pid === 0)
                .map(item => ({
                    ...item,
                    checked: false,
                    label: item.value,
                    order: 0
                }));


            // getUserValuesList.value = mockData.data;
            // initOptionStructure(); // 初始化option结构
            console.log(getUserValuesList)

        } else {
            //   ElMessage.error('获取用户导出字段');
        }

    } catch (error) {
        console.error('获取用户导出字段:', error);
        // ElMessage.error('获取用户导出字段');
    }
};

// 初始化
onMounted(async () => {
    loading.value = true;

    const siteAdminList = JSON.parse(localStorage.getItem('siteAdminList')) || [];
    const siteId = route.query.site;

    // 先加载项目列表和用户字段数据
    // 修改为
    // await Promise.all([fetchProjects(), getUserValues()]);
    await Promise.all([fetchProjects2(), getUserValues2()]);

    if(siteId){
        isEditMode.value = true; 
    }
    initOptionStructure();

    console.log('form.option:', form.option);


    // return

    if (siteId) {
        const site = siteAdminList.find(s => s.id == siteId);
        if (site) {

            // 1. 先填充基本字段
            const { option, ...siteData } = site;
            Object.assign(form, siteData);

            // 处理地区数据 - 根据中文名称查找对应的行政区划代码
            let provinceCode = '';
            let cityCode = '';

            // 查找省份代码
            const provinceObj = areaOptions.value.find(
                province => province.label === site.province
            );

            if (provinceObj) {
                provinceCode = provinceObj.value;

                // 查找城市代码
                if (provinceObj.children) {
                    const cityObj = provinceObj.children.find(
                        city => city.label === site.city
                    );

                    if (cityObj) {
                        cityCode = cityObj.value;
                    }
                }
            }

            // 设置地区选择器值
            if (provinceCode) {
                if (cityCode) {
                    form.area = [provinceCode, cityCode];
                } else {
                    form.area = [provinceCode];
                }
            }

            // 处理留资导出配置
            if (site.option) {
                try {
                    const savedOptions = typeof site.option === 'string'
                        ? JSON.parse(site.option)
                        : site.option;

                        console.log(savedOptions)


                        savedOptions.forEach((item,index) => {
                            if (item.pid === 0) { // 系统字段
                                form.option.systemFields[item.key] = {
                                    key: item.key,
                                    pid: item.pid,
                                    checked: true, // 选中状态
                                    label: item.value, // 显示的标签
                                    value: item.value, // 显示的标签
                                    order: item.order // 顺序
                                }; 
                            } else { // 项目字段
                                form.option.projectFields[`${item.pid}_${item.key}`] = {
                                    key: item.key,
                                    pid: item.pid,
                                    checked: true, // 选中状态
                                    label: item.value, // 显示的标签
                                    value: item.value, // 显示的标签
                                    order: item.order // 顺序
                                };
                            }
                            // 找到最大的order 然后赋值给selectionOrderCounter
                            if (item.order > selectionOrderCounter.value) {
                                selectionOrderCounter.value = item.order + 1;
                            }
                        })


                } catch (e) {
                    console.error('配置解析失败:', e);
                }

                
            }

        }
    }

    loading.value = false;
});

onUnmounted(() => {
    window.removeEventListener('updateSiteList', () => { });
});
</script>

<style scoped>
body {
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
    background-color: #f5f7fa;
    color: #333;
    line-height: 1.6;
}

.create-site-container {
    max-width: 80vw;
    margin: 20px auto;
    padding: 20px;
    position: relative;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 999;
}

.loading-spinner {
    width: 50px;
    height: 50px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3a7bb8;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 15px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.loading-text {
    font-size: 16px;
    color: #3a7bb8;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.header h2 {
    color: #303133;
    font-weight: 500;
    font-size: 24px;
}

.card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-bottom: 25px;
    transition: all 0.3s ease;
}

.card:hover {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.card-header {
    padding: 18px 25px;
    border-bottom: 1px solid #ebeef5;
    font-size: 18px;
    color: #303133;
    font-weight: 600;
    background: linear-gradient(to right, #f8fafc, #eef5ff);
}

.card-body {
    padding: 25px;
}

.form-section {
    margin-bottom: 25px;
    padding: 15px;
    background: #f9fbfd;
    border-radius: 8px;
}

.form-title {
    font-size: 17px;
    color: #3a7bb8;
    margin-bottom: 15px;
    padding-left: 10px;
    border-left: 4px solid #3a7bb8;
    font-weight: 600;
}

.form-row {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10px;
}

.form-col {
    flex: 0 0 33.333%;
    max-width: 33.333%;
    padding: 0 10px;
    margin-bottom: 20px;
}

.tag-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;
    min-height: 40px;
    padding: 10px;
    background: #fff;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
}

.tag-item {
    display: flex;
    align-items: center;
    background: #ecf5ff;
    color: #3a7bb8;
    border: 1px solid #d9ecff;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 14px;
    transition: all 0.2s;
}

.tag-item:hover {
    background: #d9ecff;
    transform: translateY(-2px);
}

.tag-remove {
    margin-left: 8px;
    cursor: pointer;
    color: #3a7bb8;
    font-size: 16px;
    font-weight: bold;
}

.tag-remove:hover {
    color: #f56c6c;
}

.empty-tags {
    color: #909399;
    font-style: italic;
}

.add-tag {
    display: flex;
    margin-top: 15px;
}

.add-tag-input {
    flex: 1;
    margin-right: 10px;
}

.form-actions {
    display: flex;
    justify-content: center;
    padding: 25px 0;
    gap: 20px;
}

.required-label::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
}

.site-preview {
    margin-top: 30px;
    padding: 25px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    background: #f8fafc;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.preview-header {
    font-size: 18px;
    margin-bottom: 20px;
    color: #303133;
    font-weight: 600;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.preview-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
}

.preview-item {
    background: #fff;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    transition: all 0.2s;
}

.preview-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
}

.preview-item.full-width {
    grid-column: 1 / -1;
}

.preview-label {
    font-size: 13px;
    color: #909399;
    margin-bottom: 5px;
}

.preview-value {
    font-size: 15px;
    color: #303133;
    font-weight: 500;
}

.options-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 5px;
}

.option-item {
    background: #ecf5ff;
    color: #3a7bb8;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 13px;
}

.empty-options {
    color: #909399;
    font-style: italic;
}

.option-description {
    font-size: 14px;
    color: #606266;
    margin-top: 5px;
    margin-bottom: 15px;
}

@media (max-width: 992px) {
    .form-col {
        flex: 0 0 50%;
        max-width: 50%;
    }

    .create-site-container {
        max-width: 95vw;
        padding: 15px;
    }
}

@media (max-width: 768px) {
    .form-col {
        flex: 0 0 100%;
        max-width: 100%;
    }

    .header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }

    .form-actions {
        flex-direction: column;
    }

    .preview-grid {
        grid-template-columns: 1fr;
    }
}
</style>
<style scoped>
/* 新增样式 */
.field-section {
    margin-top: 25px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    background-color: #f8fafc;
}

.field-title {
    font-size: 16px;
    color: #3a7bb8;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 1px dashed #dcdfe6;
}

.field-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
    gap: 15px;
}

.field-item {
    display: flex;
    flex-direction: column;
    padding: 12px;
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    transition: all 0.2s;
}

.field-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.08);
}

.field-checkbox {
    margin-bottom: 8px;
}

.field-identifier {
    font-size: 12px;
    color: #909399;
    margin-bottom: 8px;
}

.field-input {
    width: 100%;
}

.preview-category {
    margin-bottom: 15px;
}

.preview-category-title {
    font-weight: 600;
    color: #3a7bb8;
    margin-bottom: 8px;
    font-size: 14px;
}

.options-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.option-item {
    background: #ecf5ff;
    color: #3a7bb8;
    padding: 6px 12px;
    border-radius: 15px;
    font-size: 13px;
    border: 1px solid #d9ecff;
}

.empty-options {
    color: #909399;
    font-style: italic;
}

@media (max-width: 768px) {
    .field-container {
        grid-template-columns: 1fr;
    }
}



.field-item {
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    transition: all 0.2s;
}

.field-item:hover {
    border-color: #dcdfe6;
    background-color: #fafafa;
}

.field-checkbox {
    margin-bottom: 8px;
}

.field-identifier {
    color: #606266;
    font-size: 12px;
    margin-bottom: 8px;
}
</style>
